package cn.chencq.spider.novel.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.chencq.spider.novel.vo.Selector;

public class SpiderRuleUtils {

	private static final Map<String, Selector> CONTEXT_MAP = new HashMap<String, Selector>();

	static {
		init("Spider-Rule.xml");
	}

	private SpiderRuleUtils() {
	}

	@SuppressWarnings("unchecked")
	public static void init(String configFilePath) {
		SAXReader reader = new SAXReader();
		InputStream is = null;
		try {
			is = SpiderRuleUtils.class
					.getResourceAsStream("/" + configFilePath);
			if (is == null) {
				is = new FileInputStream(configFilePath);
			}
			Document doc = reader.read(is);
			Element root = doc.getRootElement();
			List<Element> sites = root.elements("site");
			for (Element site : sites) {
				List<Element> els = site.elements();
				Selector selector = new Selector();
				for (Element el : els) {
					String elName = el.getName();
					String value = el.getText();
					switch (elName) {
					case "name":
						selector.setName(value);
						break;
					case "charset":
						selector.setCharset(value);
						break;
					case "domain":
						selector.setDomain(value);
						break;
					case "book-list-selector":
						selector.setBookListSelector(value);
						break;
					case "book-name-selector":
						selector.setBookNameSelector(value);
						break;
					case "book-author-selector":
						selector.setBookAuthorSelector(value);
						break;
					case "book-url-selector":
						selector.setBookUrlSelector(value);
						break;
					case "book-type-selector":
						selector.setBookTypeSelector(value);
						break;
					case "book-status-selector":
						selector.setBookStatusSelector(value);
						break;
					case "newchapter-name-selector":
						selector.setNewChapterNameSelector(value);
						break;
					case "newchapter-url-selector":
						selector.setNewChapterUrlSelector(value);
						break;
					case "newchapter-updatetime-selector":
						selector.setNewChapterUpdateTimeSelector(value);
						break;
					case "chapter-list-selector":
						selector.setChapterListSelector(value);
						break;
					case "chapter-detail-title-selector":
						selector.setChapterDetailTitelSelector(value);
						break;
					case "chapter-detail-content-selector":
						selector.setChapterDetailContentSelector(value);
						break;
					case "chapter-detail-prev-selector":
						selector.setChapterDetailPrevSelector(value);
						break;
					case "chapter-detail-next-selector":
						selector.setChapterDetailNextSelector(value);
						break;
					default:
						break;
					}
				}
				CONTEXT_MAP.put(selector.getDomain(), selector);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Selector getSpiderSelector(String domain) {
		return CONTEXT_MAP.get(domain);
	}
}
